<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        :placeholder="$t('昵称')"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.roles"
        :placeholder="$t('角色')"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarRolesOptions"
          :key="item.key"
          :label="item.display_name + '(' + item.key + ')'"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.sort"
        style="width: 140px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t("table.search") }}
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t("table.add") }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        :label="$t('用户ID')"
        prop="uid"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('uid')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.uid }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('用户名')" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('昵称')" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('介绍')" width="220px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.introduction }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('角色')" width="110px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.roles }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('部门')" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.department }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button v-if="row.uid <= 2" type="info" size="mini" disabled>
            {{ $t("测试用例无法操作") }}
          </el-button>
          <el-button
            v-if="row.uid > 2"
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            {{ $t("table.edit") }}
          </el-button>
          <el-button
            v-if="row.uid > 2"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ $t("table.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 创建用户 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('用户名')" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item :label="$t('密码')" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item :label="$t('昵称')" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <!-- 角色 -->
        <el-form-item :label="$t('角色')" prop="roles">
          <el-select
            v-model="temp.roles"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in calendarRolesOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <!-- 部门 -->
        <el-form-item :label="$t('部门')" prop="department">
          <el-select
            v-model="temp.department"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in calendarDepartmentOptions"
              :key="item.id"
              :label="item.department"
              :value="item.department"
            />
          </el-select>
        </el-form-item>
        <!-- 头像 -->
        <el-form-item :label="$t('头像')" prop="avatar">
          <el-select
            v-model="temp.avatar"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in calendarAvatarOptions"
              :key="item.id"
              :label="item.display_name"
              :value="item.url"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('自我介绍')" prop="introduction">
          <el-input v-model="temp.introduction" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="createData()">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogEditFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item :label="$t('用户名')" prop="username">
          <el-input v-model="temp.username" disabled />
        </el-form-item>
        <el-form-item :label="$t('密码')" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item :label="$t('昵称')" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <!-- 角色 -->
        <el-form-item :label="$t('角色')" prop="roles">
          <el-select
            v-model="temp.roles"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in calendarRolesOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <!-- 部门 -->
        <el-form-item :label="$t('部门')" prop="department">
          <el-select
            v-model="temp.department"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in calendarDepartmentOptions"
              :key="item.id"
              :label="item.department"
              :value="item.department"
            />
          </el-select>
        </el-form-item>
        <!-- 头像 -->
        <el-form-item :label="$t('头像')" prop="avatar">
          <el-select
            v-model="temp.avatar"
            class="filter-item"
            placeholder="Please select"
          >
            <el-option
              v-for="item in calendarAvatarOptions"
              :key="item.id"
              :label="item.display_name"
              :value="item.url"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('自我介绍')" prop="introduction">
          <el-input v-model="temp.introduction" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="updateData()">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{
          $t("table.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchPv,
  createUser,
  updateUser,
  deleteUser,
} from "@/api/system";
import { getPictureList } from "@/api/picture";
import { getDepartmentList } from "@/api/department";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { validUsername } from "@/utils/validate";

// 选择角色
let calendarRolesOptions = [
  { key: "admin", display_name: "admin" },
  { key: "editor", display_name: "editor" },
  { key: "visitor", display_name: "visitor" },
];

// 选择头像
let calendarAvatarOptions = [];

// 选择部门
let calendarDepartmentOptions = [];

// arr to obj, such as { CN : "China", US : "USA" }
let calendarRolesKeyValue = calendarRolesOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

let calendarAvatarKeyValue = calendarAvatarOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

let calendarDepartmentKeyValue = calendarDepartmentOptions.reduce(
  (acc, cur) => {
    acc[cur.department] = cur.department;
    return acc;
  },
  {}
);

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    rolesFilter(roles) {
      return calendarRolesKeyValue[roles];
    },
    avatarFilter(avatar) {
      return calendarAvatarKeyValue[avatar];
    },
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("账户名由5~12位字母数字组成，请检查"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不少于六位"));
      } else {
        callback();
      }
    };
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        roles: undefined,
        sort: "+uid",
      },
      calendarRolesOptions,
      calendarAvatarOptions,
      calendarDepartmentOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+uid" },
        { label: "ID Descending", key: "-uid" },
      ],
      temp: {
        uid: undefined,
        username: undefined,
        name: undefined,
        password: "",
        avatar: "",
        introduction: "",
        department: "",
      },
      dialogFormVisible: false,
      dialogEditFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        username: [
          { required: true, validator: validateUsername, trigger: "blur" },
        ],
        password: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        // 昵称
        name: [
          { required: true, message: "name is required", trigger: "blur" },
        ],
        department: [
          {
            required: true,
            message: "department is required",
            trigger: "blur",
          },
        ],
        roles: [{ required: true, message: "please select", trigger: "blur" }],
        avatar: [{ required: true, message: "please select", trigger: "blur" }],
      },
      downloadLoading: false,
    };
  },
  created() {
    this.getList();
    getPictureList().then((response) => {
      this.calendarAvatarOptions = response.data.items;
    });
    getDepartmentList().then((response) => {
      this.calendarDepartmentOptions = response.data.items;
    });
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then((response) => {
        this.list = response.data.items;
        this.total = response.data.total;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "uid") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+uid";
      } else {
        this.listQuery.sort = "-uid";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        uid: undefined,
        username: undefined,
        name: undefined,
        password: "",
        avatar: "",
        introduction: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          createUser(this.temp).then((res) => {
            this.temp.uid = res.data;
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "update";
      this.dialogEditFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          updateUser(tempData).then(() => {
            const index = this.list.findIndex((v) => v.uid === this.temp.uid);
            this.list.splice(index, 1, this.temp);
            this.dialogEditFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      deleteUser(row.uid).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
      });

      this.list.splice(index, 1);
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },

    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>
